import threading
class BankAccount:
    def __init__(self, balance):
        self.balance = balance
        self.lock = threading.Lock()

    def transfer(self, target, amount):
        # 按固定顺序获取锁（避免死锁）
        lock1, lock2 = sorted([self.lock, target.lock], key=id)

        with lock1:
            with lock2:
                if self.balance >= amount:
                    self.balance -= amount
                    target.balance += amount
                    return True
        return False


# 使用示例
account_a = BankAccount(1000)
account_b = BankAccount(1000)


def transfer_worker():
    for _ in range(100):
        # 随机选择转账方向
        if threading.get_ident() % 2 == 0:
            account_a.transfer(account_b, 1)
        else:
            account_b.transfer(account_a, 1)


threads = []
for _ in range(10):
    t = threading.Thread(target=transfer_worker)
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print(f"Account A balance: {account_a.balance}")
print(f"Account B balance: {account_b.balance}")
print(f"Total balance: {account_a.balance + account_b.balance}")  # 应该保持2000